package com.bookocean.infrastructure.persistence.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bookocean.infrastructure.persistence.po.UserPointsPO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 用户积分 Mapper 接口
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Mapper
public interface UserPointsMapper extends BaseMapper<UserPointsPO> {

    /**
     * 查询用户积分信息
     * 
     * @param userId 用户ID
     * @return 用户积分信息
     */
    @Select("SELECT * FROM user_points_po WHERE user_id = #{userId}")
    UserPointsPO selectUserPoints(@Param("userId") Long userId);

    /**
     * 更新用户积分
     * 
     * @param userId 用户ID
     * @param points 积分变化量（正数为增加，负数为减少）
     * @return 影响行数
     */
    @Update("UPDATE user_points_po SET " +
            "total_points = total_points + #{points}, " +
            "available_points = available_points + #{points}, " +
            "updated_at = NOW() " +
            "WHERE user_id = #{userId}")
    int updateUserPoints(@Param("userId") Long userId, @Param("points") Integer points);

    /**
     * 消费用户积分
     * 
     * @param userId 用户ID
     * @param points 消费积分数量
     * @return 影响行数
     */
    @Update("UPDATE user_points_po SET " +
            "available_points = available_points - #{points}, " +
            "updated_at = NOW() " +
            "WHERE user_id = #{userId} AND available_points >= #{points}")
    int consumeUserPoints(@Param("userId") Long userId, @Param("points") Integer points);
}
